package com.zjh.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    public static String driver;
    public static String url;
    public static String username;
    public static String password;

    static {
        Properties properties = new Properties();
        InputStream input = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //查
    public static ResultSet execute(Connection connection, ResultSet rs, PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }

        rs = preparedStatement.executeQuery();
        return rs;
    }

    //增删改
    public static int execute(Connection connection, PreparedStatement pstm,String sql, Object[] params) throws SQLException {
        pstm = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            pstm.setObject(i + 1, params[i]);
        }

        int updateRows = pstm.executeUpdate();
        return updateRows;
    }

    public static boolean CloseResource(Connection connection, PreparedStatement preparedStatement, ResultSet rs) {
        boolean flag = true;
        try {
            if (rs != null) {
                rs.close();
//                GC回收
                rs = null;
            }
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            flag = false;
        }

        return flag;
    }

}
